import {
	loginTradeUser
} from "@/src/api/login.js";
import {
	getApiBaseUrl,
	isDevelopment
} from './src/utils/env.js'

// 防止重复跳转登录页的锁
let isHandling401 = false;
const base_url = getApiBaseUrl()
// console.log("配置base_url------",base_url)
const request = (params) => {
	let url = params.url;;
	let method = params.method || "get";
	let data = params.data || {};
	let header = {
		'Content-Type': 'application/json'
	};

	// token
	if (uni.getStorageSync("token")) {
		header['Authorization'] = 'Bearer ' + uni.getStorageSync("token");
	}
	// 语言
	header['langt'] = uni.getStorageSync("langt") || "0";

	return new Promise((resolve, reject) => {
		uni.request({
			url: base_url + url,
			method: method,
			header: header,
			data: data,
			success(response) {
				const res = response
				// 根据返回的状态码做出对应的操作
				// 获取成功
				if (res.statusCode == 200) {
					resolve(res.data);
				} else {
					let langt = uni.getStorageSync("langt") || "0";
					let msgTip = "";

					switch (res.statusCode) {
						case 401:
							// 清除缓存
							try {
								uni.removeStorageSync("token");
							} catch (e) {}

							try {
								uni.removeStorageSync("userInfo");
							} catch (e) {}
							// 判断是否是登录页
							let isLoginPage = false;
							let routes = getCurrentPages();
							let pUrl = routes[routes.length - 1].route;
							if (pUrl.indexOf("/login/login") > -1 || pUrl.indexOf("pages/") == -1) {
								isLoginPage = true;
							}
							if (isLoginPage) {
								// 登录页面
								reject({
									code: 1
								});
							} else {
								if (isHandling401) return;
								isHandling401 = true;
								msgTip = langt == "1" ? "请登录" : "Please log in";
								uni.showModal({
									title: "  ",
									confirmColor: 'black', // 确定按钮颜色（默认蓝色）
									content: msgTip,
									showCancel: false,
									success(res) {
										uni.redirectTo({
											url: "/pages/login/login",
											complete: () => {
												isHandling401 = false;
											}
										})
									}
								});
							}
							break;
						case 404:
							msgTip = langt == "1" ? "请求地址不存在..." :
								"The requested address does not exist...";
							uni.showToast({
								title: msgTip,
								icon: "error",
								duration: 2000,
							})
							break;
						case 500:
							reject({
								code: 1
							});
							break;
						default:
							msgTip = langt == "1" ? "请重试..." : "Please try again";
							uni.showToast({
								title: msgTip,
								icon: "error",
								duration: 2000,
							})
							break;
					}
				}
			},
			fail(err) {
				if (err.errMsg.indexOf('request:fail') !== -1) {
					wx.showToast({
						title: '网络异常',
						icon: "error",
						duration: 2000
					})
				} else {
					wx.showToast({
						title: '未知异常',
						duration: 2000
					})
				}
				reject(err);

			},
			complete() {
				// 不管成功还是失败都会执行
				// uni.hideLoading();
				// uni.hideToast();
			}
		});
	}).catch((e) => {});
};

export default request;